package com.stone.inventory.sharding.id;


import com.stone.inventory.sharding.config.properties.GlobalIdProperties;

/**
 * 分布式Id 生成器，参考雪花算法
 *
 * @author Mr_wenpan@163.com 2021/07/28
 */
public class IdGenerator {

    /**
     * 起始时间戳 2021/01/01 00:00:00 开始
     */
    private final long begTimePoint = 1546272000000L;

    /**
     * 节点id位数
     */
    private final long nodeIdBits;

    /**
     * 表id位数
     */
    private final long tableIdBits;

    /**
     * 序列位数
     */
    private final long sequenceBits;

    /**
     * 最大节点数
     */
    private final long maxNodeId;

    /**
     * 最大分表id数
     */
    private final long maxTableId;

    /**
     * 节点id偏移量（即节点ID左移多少位）
     */
    private final long nodeIdShift;

    /**
     * 表id偏移量（即表ID左移多少位）
     */
    private final long tableIdShift;

    /**
     * 时间偏移量(即时间戳左移多少位)
     */
    private final long timestampLeftShift;

    /**
     * 毫秒内序列最大值
     */
    private final long sequenceMask;

    /**
     * 节点id
     */
    private final long nodeId;

    /**
     * 表id
     */
    private final long tableId;

    /**
     * 毫秒内序列计数
     */
    private long sequence;

    /**
     * 上一次生成id所属时间
     */
    private long lastTimestamp;

    public IdGenerator(GlobalIdProperties properties, long nodeId, long tableId) {

        this.nodeId = nodeId;
        this.tableId = tableId;
        nodeIdBits = properties.getNodeBits();
        tableIdBits = properties.getTableBits();
        sequenceBits = properties.getSequenceBits();
        // 取nodeIdBits位的最大值（比如占5位，那么maxNodeId = 2^5 = 32）
        maxNodeId = ~(-1L << nodeIdBits);
        //  取tableIdBits位的最大值
        maxTableId = ~(-1L << tableIdBits);
        nodeIdShift = sequenceBits;
        tableIdShift = sequenceBits + nodeIdBits;
        timestampLeftShift = sequenceBits + nodeIdBits + tableIdBits;
        // 取sequenceBits位的最大值
        sequenceMask = ~(-1L << sequenceBits);
        sequence = 0L;
        lastTimestamp = -1L;
        if (nodeId > maxNodeId || nodeId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxNodeId));
        }
    }

    /**
     * 生成一个id
     *
     * @return id
     */
    public synchronized long nextId() {

        long timestamp = timeGen();
        // 时间戳只能增大不能时钟回拨
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                            lastTimestamp - timestamp));
        }
        // 如果时间戳一样，则序列号增大
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            // 1s内最多允许生成多少个ID，如果已经达到最大值则阻塞到下一个毫秒
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 否则序列号从0开始
            sequence = 0L;
        }

        // 更新上次生成ID的时间戳
        lastTimestamp = timestamp;

        // 通过自定义位移算法生成指定格式的ID
        return ((timestamp - begTimePoint) << timestampLeftShift)
                | (tableId << tableIdShift)
                | (nodeId << nodeIdShift)
                | sequence;
    }

    /**
     * 阻塞到下一毫秒
     *
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳(毫秒)
     *
     * @return 当前时间(毫秒)
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }

}
